﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeadMaster.Models;
using LeadMaster.DAL;
using LeadMaster.Helpers;

namespace LeadMaster.Controllers
{
    public class PurchaseOrderController : Controller
    {
        private DunsmoreContext db = new DunsmoreContext();

        //
        // GET: /PurchaseOrder/

        public ActionResult Index(string intRef="none")
        {
            Maintenance.inMaintenance = true;
            var purchaseorders = db.PurchaseOrders.Include(p => p.Lead);
            if (intRef != "none")
            {
              purchaseorders = purchaseorders.Where(m => m.Lead.IntRef == intRef);
              ViewBag.Title = intRef;
            }

            return View(purchaseorders.ToList());
        }

        //
        // GET: /PurchaseOrder/Details/5

        public ActionResult Details(int id = 0)
        {
            PurchaseOrders purchaseorders = db.PurchaseOrders.Find(id);
            if (purchaseorders == null)
            {
                return HttpNotFound();
            }
            return View(purchaseorders);
        }

        //
        // GET: /PurchaseOrder/Create

        public ActionResult Create()
        {
            ViewBag.LeadID = new SelectList(db.Leads, "LeadID", "ContactType");
            return View();
        }

        //
        // POST: /PurchaseOrder/Create

        [HttpPost]
        public ActionResult Create(PurchaseOrders purchaseorders)
        {
            if (ModelState.IsValid)
            {
                db.PurchaseOrders.Add(purchaseorders);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.LeadID = new SelectList(db.Leads, "LeadID", "ContactType", purchaseorders.LeadID);
            return View(purchaseorders);
        }

        //
        // GET: /PurchaseOrder/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Maintenance.inMaintenance = true;
            PurchaseOrders purchaseorders = db.PurchaseOrders.Find(id);
            if (purchaseorders == null)
            {
                return HttpNotFound();
            }
            ViewBag.LeadID = new SelectList(db.Leads, "LeadID", "ContactType", purchaseorders.LeadID);
            ViewBag.CallCentreID = db.CallCentres
                          .OrderBy(m => m.CallCentre)
                          .ToList()
                             .Select(c => new SelectListItem
                             {
                               Value = c.CallCentreID.ToString(),
                               Text = c.CallCentre
                             });

            return View(purchaseorders);
        }

        //
        // POST: /PurchaseOrder/Edit/5

        [HttpPost]
        public ActionResult Edit(PurchaseOrders purchaseorders)
        {
            if (ModelState.IsValid)
            {
                LeadStatus leadStatus = db.LeadStatus.Where(m => m.PurchaseOrderID == purchaseorders.PurchaseOrderID).FirstOrDefault();
                if (leadStatus == null)
                {
                  purchaseorders.Deficit = purchaseorders.Quantity;
                }
                db.Entry(purchaseorders).State = EntityState.Modified;
                db.SaveChanges();
                string pid = purchaseorders.PID;
                purchaseorders = null;
                if (leadStatus != null)
                {
                  GenericRepository gr = new GenericRepository();
                  bool poChanged = gr.RefreshPO(pid);
                }
                return RedirectToAction("Index");
            }
            ViewBag.LeadID = new SelectList(db.Leads, "LeadID", "ContactType", purchaseorders.LeadID);
            return View(purchaseorders);
        }

        //
        // GET: /PurchaseOrder/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Maintenance.inMaintenance = true;
            PurchaseOrders purchaseorders = db.PurchaseOrders.Find(id);
            if (purchaseorders == null)
            {
                return HttpNotFound();
            }
            return View(purchaseorders);
        }

        //
        // POST: /PurchaseOrder/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int PurchaseOrderID)
        {
            PurchaseOrders purchaseorders = db.PurchaseOrders.Find(PurchaseOrderID);
            db.PurchaseOrders.Remove(purchaseorders);
            try
            {
              db.SaveChanges();
            }
            catch (Exception)
            {
              ViewBag.ErrorMessage = "Sorry - you can not delete this Purchase Order as it is already active in other processes.";
              return View("Errormessages");
            }

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public RedirectResult Paid(string pid)
        {
            PurchaseOrders pOrder = db.PurchaseOrders.Where(m => m.PID == pid).First();
            pOrder.Paid = true;
            pOrder.DatePaidCC = DateTime.Now;
            db.Entry(pOrder).State = EntityState.Modified;
            db.SaveChanges();
            return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fCompletedPurchaseOrders&rs:Command=Render");
        }

        public void Terminate(string pid)
        {
            PurchaseOrders pOrder = db.PurchaseOrders.Where(m => m.PID == pid).FirstOrDefault();
            pOrder.Deficit = 0;
            pOrder.terminated = true;
            CallCentres cc = db.CallCentres.Find(pOrder.CallCentreID);
            OracMailMessage mm = new OracMailMessage();
            mm.EmailTo = cc.Email1;
            mm.cc = "karlosmalin@gmail.com";
            //mm.cc = "david@dunsmoremarketing.co.uk, james.parsons@Sawford-Bullard.co.uk, admin@dunsmoremarketing.co.uk";
            mm.EmailSubject = "Notice of Order Termination";
            mm.EmailBody = "Please note that Order Number " + pOrder.PID.Trim() + " has been terminated.";
            if (pOrder.ClientPaid??false==false)
            {
                pOrder.BalanceToPay = 0;
                pOrder.Notes += "\nOrder has been terminated. The Client has not paid and so unfortunately, we can not pay " + cc.CallCentre.Trim() + " for any work that has been undertaken.";
                mm.EmailBody += "\nThe Client has not paid and so unfortunately, we can not pay " + cc.CallCentre.Trim() + " for any work that has been undertaken.";
                mm.EmailBody += "\nWe apologise for this and hope that this news was understood before all agreed the campaign must stop.";
                mm.EmailBody += "\n\nThis is an automated email from Orac. Please do not reply.";
            }
            else
            {
                pOrder.Notes += "\nOrder has been terminated. We will be paying " + cc.CallCentre.Trim() + " the outstanding balance for leads supplied and accepted.";
                mm.EmailBody += "\nWe will be paying " + cc.CallCentre.Trim() + " the outstanding balance for leads supplied and accepted.";
                mm.EmailBody += "\n\nThis is an automated email from Orac. Please do not reply.";
            }
            db.Entry(pOrder).State = EntityState.Modified;
            db.SaveChanges();
            mm.SendEmail();
        }

        public RedirectResult OutsourcerTracker(int callCentreID)
        {
            return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fOutsourcerTracker&rs:Command=Render&c=" + callCentreID.ToString());
        }
    }
}